package top.ninwoo.client.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import top.ninwoo.bishe.starter.service.NetworkService;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@RestController
public class TestController {
    @Resource
    private NetworkService networkService;

    @GetMapping("/start")
    public String start(String ip, String t, String selfName, String targetName, float div) {
        int i = (int) (40 * div);
        networkService.addQos(11111L, targetName, i + "mbit", "100ms");
        networkService.addQos(11111L, selfName, (40 - i) +"mbit", "100ms");
        runCmd("iperf -c " + ip + " -t " + t);
        networkService.addQos(11111L, targetName,  "40mbit", "100ms");
        return "success";
    }

    private String runCmd(String cmd) {
        String result = "";
        try {
            Process exec = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd});
            exec.waitFor();
            InputStream in = exec.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String msg;
            while((msg = br.readLine())!= null && msg.length() > 0) {
                result += msg + "\n";
            }

            if("".equals(result)) {
                // 构建Error
                InputStream errorStream = exec.getErrorStream();
                BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream));
                String eMsg;
                while((eMsg = ebr.readLine())!= null && eMsg.length() > 0) {
                    result += eMsg + "\n";
                }
                if(result.equals("")) {
                    return result;
                }
                result = "Error: " + result;
            }
            if(result.length() > 0) {
                result = result.substring(0, result.length()-1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }
}
